﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sami_SMS_CRM_Business;
using System.Web.Services;

namespace Sami_SMS_CRM_UI
{
    public partial class crm_subscribers : BasePage
    {
        SubscriberRepository repository = new SubscriberRepository();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindDataTable();
            pagingtop.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
                pagingtop.CurrentPage = 1;
                pagingtop.PageSize = PageSize;
                pagingtop.PageDisplay = PageDisPlay;
                pagingbottom.CurrentPage = 1;
                pagingbottom.PageSize = PageSize;
                pagingbottom.PageDisplay = PageDisPlay;
                BindDataTable();
            }
        }

        private void BindDataTable()
        {
            int currentPage = pagingtop.CurrentPage;
            int pageSize = pagingtop.PageSize;
            int totalRecord = 0;

            string subs = txtSubscriber.Text.Trim();
            bool? enable = ddlEnable.SelectedValue == "true" ? true : (ddlEnable.SelectedValue == "false" ? false : (bool?)null);

            rptTable.DataSource = repository.GetAll(currentPage, pageSize, ref totalRecord, subs, enable);
            rptTable.DataBind();

            pagingtop.TotalRecord = totalRecord;
            pagingtop.Visible = pagingtop.TotalPage > 1;
            pagingbottom.TotalRecord = totalRecord;
            pagingbottom.Visible = pagingtop.TotalPage > 1;
            ltrTotalRow.Text = totalRecord.ToString();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            pagingtop.PageSize = pagingbottom.PageSize = int.Parse((sender as DropDownList).SelectedValue);
            BindDataTable();
        }

        protected void btnSearching_Click(object sender, EventArgs e)
        {
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            BindDataTable();
        }

        protected void btnAddNew_Click(object sender, ImageClickEventArgs e)
        {
            SetData(null);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog1');", true);
        }

        protected void rptTable_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (IsAdmin())
                {
                    string id = e.CommandArgument.ToString();
                    switch (e.CommandName)
                    {
                        case "Edited":
                            var entity = repository.GetById(id);
                            SetData(entity);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog1');", true);
                            break;
                        case "Deleted":
                            repository.DeleteById(id);
                            BindDataTable();
                            break;
                        case "ViewDetail":
                            ViewDetail(id);
                            break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"You don't have permission!\");", true);
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        private void SetData(Sami_SMS_CRM_Business.crm_subscriber entity)
        {
            if (entity != null)
            {
                hdfAction.Value = "Edit";
                hdfId.Value = entity.subscriber;
                txtSubs.Text = entity.subscriber;
                txtSubs.Enabled = false;
                txtFullName.Text = entity.full_name;
                txtDateOfBirth.Text = entity.date_of_birth.HasValue ? entity.date_of_birth.Value.ToShortDateString() : string.Empty;
                txtAddress.Text = entity.address;
                txtNote.Text = entity.note;
                ddlGender.SelectedValue = entity.gender.ToString();
                ddlEnabled.SelectedValue = entity.enabled.ToString();

            }
            else
            {
                hdfAction.Value = "AddNew";
                hdfId.Value = string.Empty;
                txtSubs.Text = string.Empty;
                txtFullName.Text = string.Empty;
                txtDateOfBirth.Text = string.Empty;
                txtAddress.Text = string.Empty;
                txtNote.Text = string.Empty;
                ddlGender.SelectedIndex = 0;
                ddlEnabled.SelectedIndex = 0;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckFullInfo())
                {
                    Sami_SMS_CRM_Business.crm_subscriber entity = repository.GetById(hdfId.Value) ?? new Sami_SMS_CRM_Business.crm_subscriber();
                    entity.full_name = txtFullName.Text;
                    entity.address = txtAddress.Text;
                    entity.note = txtNote.Text;
                    entity.gender = bool.Parse(ddlGender.SelectedValue);
                    entity.date_of_birth = (string.IsNullOrEmpty(txtDateOfBirth.Text.Trim()) ? (DateTime?)null : DateTime.Parse(txtDateOfBirth.Text, DateTimeFormat));
                    entity.enabled = bool.Parse(ddlEnabled.SelectedValue);
                    switch (hdfAction.Value)
                    {
                        case "Edit":
                            repository.Update(entity);
                            BindDataTable();
                            break;
                        case "AddNew":
                            entity.subscriber = txtSubs.Text.Trim();
                            repository.AddNew(entity);
                            BindDataTable();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        private bool CheckFullInfo()
        {
            string errMsg = string.Empty;
            if(string.IsNullOrEmpty(txtSubs.Text.Trim()))
                errMsg="Subscriber not allow null";
            if (errMsg == string.Empty)
            {
                return true;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + errMsg + "\"); OpenDialog('dialog1');", true);
                return false;
            }
        }

        private void ViewDetail(string subscriber)
        {
            rptSubsService.DataSource = DB.crm_service_subscribers
                                .Where(p => p.subscriber == subscriber)
                                .Join(DB.crm_services,
                                        outer => outer.service_id,
                                        inner => inner.sevice_id,
                                        (outer, inner) => new
                                        {
                                            outer.subscriber,
                                            outer.service_id,
                                            inner.service_name,
                                            outer.used_counter,
                                            outer.vasp_num,
                                            outer.lastest_used,
                                            outer.advertisement_previous_sent,
                                            outer.advertisement_lastest_sent,
                                            outer.advertisement_counter,
                                            outer.measurement,
                                            enabled = outer.enabled ?? true
                                        })
                                    .OrderBy(p => p.service_name);
            rptSubsService.DataBind();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog2',1000,678);", true);
        }

        [WebMethod]
        public static bool EnableServiceSubscriber(string subscriber, int serviceId, bool enable)
        {
            try
            {
                DBDataContext db = new DBDataContext(Settings.LocalSettings.ConnectionString);
                var entity = db.crm_service_subscribers
                            .FirstOrDefault(p => p.subscriber == subscriber && p.service_id == serviceId);
                if (entity != null)
                {
                    entity.enabled = enable;
                    db.SubmitChanges();
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
}